package com.zhiwen.controller;

import com.zhiwen.util.DistributedLock;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @Auther: wuzhiwen
 * @Date: 2018/11/12 12:29
 * @Description:
 */
public class CuratorDistributed {

    public static void main(String[] args) {

        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    //创建zookeeper的客户端
                    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
//                    CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.91.129:2181,192.168.91.129:2182,192.168.91.129:2183", retryPolicy);
                    CuratorFramework client = CuratorFrameworkFactory.newClient("192.168.91.129:2181", retryPolicy);
                    client.start();
                    //创建分布式锁, 锁空间的根节点路径为/curator/lock
                    InterProcessMutex mutex = new InterProcessMutex(client, "/rootCurator/lock");
                    mutex.acquire();
                    //获得了锁, 进行业务流程
                    System.out.println("业务运行成功");
                    //完成业务流程, 释放锁
                    mutex.release();
                    //关闭客户端
                    client.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(runnable);
            t.start();
        }
    }
}
